<template>
  <el-tree-select
    v-model="expenseLedgerId"
    :data="expenseLedgerList"
    :check-strictly="checkStrictly"
    :render-after-expand="false"
    style="width: 240px"
  >
    <template #default="{ data: { label } }">
      <el-tooltip class="box-item" effect="dark" :content="label">
        {{ label }}
      </el-tooltip></template
    >
  </el-tree-select>
</template>
<script>
import { expenseLedger } from "@/api/expense.ts";
import { handleTree } from "@/utils/tree.ts";
function findId(tree, pid) {
  for (let c of tree) {
    if (c.value === pid) {
      return c.children;
    }
    if (c.children?.length) {
      let res = findId(c.children, pid);
      if (res?.length) return res;
    }
  }
  return [];
}
export default {
  name: "expenseLedgerSelector",
  props: {
    modelValue: String,
    parentId: String,
    checkStrictly: {
      type: Boolean,
      default() {
        return true;
      }
    }
  },
  emits: ["update:modelValue"],
  data() {
    return {
      expenseLedgerList: [],
      keyword: "",
      expenseLedgerId: ""
    };
  },
  watch: {
    expenseLedgerId(nv) {
      this.$emit("update:modelValue", nv);
    }
  },
  async mounted() {
    let res = await expenseLedger();
    if (res.code === 200) {
      let tree = handleTree(
        res.data
          .sort(
            (a, b) => parseFloat(a.serialNumber) - parseFloat(b.serialNumber)
          )
          .map(({ id, pid, ledger, serialNumber }) => {
            let label = serialNumber.includes("x")
              ? ledger
              : serialNumber + " " + ledger;
            return { pid, value: id, label: label };
          }),
        "value",
        "pid"
      );
      if (this.parentId) {
        this.expenseLedgerList = findId(tree, this.parentId);
      } else {
        this.expenseLedgerList = tree;
      }

      console.log(this.expenseLedgerList, this.parentId, tree);
    }
  }
};
</script>
